package src.percolation;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import src.utils.Utils;

public class Pr4 {

	private static final double pc = 0.596;
	
	public static void main(String[] argvs) throws IOException {
	
		
		int netSize;

		double minProba;
		double maxProba;
		double eps;
		String outputName;

		try {
			netSize = new Integer(argvs[0]);
			minProba = new Double(argvs[1]);
			maxProba = new Double(argvs[2]);
			eps = new Double(argvs[3]);
			outputName =  argvs[4];
			
		} catch (Exception e) {
			showUsage();
			return;
		}
		
		Random gen = new Random();
		long seed = gen.nextLong();
		
		runSimulation(minProba, maxProba, eps, outputName,netSize,gen);
	
	}
	public static void runSimulation(double initProba, double finalProba, double eps, String fileName,int large, Random generator) throws IOException {
		
		Map<Double,Double> results = new TreeMap<Double, Double>();
		
		Red myRed;
		
		for(double probability = initProba; probability<finalProba; probability += eps) {

			
			myRed = generateValidGrid(probability,large,generator);
			
			//take the result
			double radius = myRed.getRadius();
			results.put(probability, radius);
		}
		Utils.printToFile(results, fileName);	
	}
	
	private static Red generateValidGrid(double probability,int large, Random generator) {
		
		Red myRed;
		if(probability<pc){
			do{
				myRed = new Red(large,generator.nextLong());
				myRed.createGrid(probability); //initialize it
			} while(myRed.doesPercolate());
		}else{
			do{
				myRed = new Red(large,generator.nextLong());
				myRed.createGrid(probability); //initialize it
			} while(!myRed.doesPercolate());
		}
		return myRed;
	}
	
	private static void showUsage() {
		System.out.println("Usage: ");
		
		System.out.println("<netSize> <minProba> <maxProba> <increment> <eps> <meanOutFile> <sigmaOutFile>\n");
		
		System.out.println("<netSize>: size of net.");
		System.out.println("<minProba>: minimum probability.");
		System.out.println("<maxProba>: maximum probability.");
		System.out.println("<increment>: increment between probabilities.");
		System.out.println("<output name>: name for the output file.");
	}
}
